package com.braveman.im.ui.activity.message;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.braveman.im.R;
import com.braveman.im.bean.CreateGroupInfoBean;
import com.braveman.im.bean.PicUpdateBean;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.thread.CompressPhotoThread;
import com.braveman.im.ui.weiget.ClearEditText;
import com.braveman.im.ui.weiget.CustomPopwindow;
import com.braveman.im.ui.weiget.DialogUtils;
import com.braveman.im.utils.PermissionUtils;
import com.braveman.im.utils.UtilsStyle;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.UIUtils;
import com.vondear.rxtools.RxBarTool;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

public class CreateGroupOnlyActivity extends BaseActivity {
    private ClearEditText mCetActivityCreateGroupProposer;
    private ClearEditText mCetActivityCreateGroupName;
    private ClearEditText mCetActivityCreateGroupCompanyIntroduce;
    private ImageView mIvActivityCreateGroupCompanyIcon;
    private Spinner mSpActivityStates;
    private TextView mBtnActivityCreateGroupUpdate;
    private static final String TAKE_PHOTO_PATH = "ht/jkm/photo/GROUP_ONLY_INFO.jpg";
    private static final int REQUEST_CODE_TAKE_PHOTO = 1;
    private static final int REQUEST_CODE_TAKE_ICON_PHOTO = 4;
    private static final int REQUEST_CAMERA_CODE = 2;
    private static final int REQUEST_CAMERA_ICON_CODE = 3;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 0;
    private static final int MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD = 1;
    private String picturePath;
    private String picUrl;
    private String groupCategoryId;
    private String picturePath1;
    private String picUrl1;
    private List<String> list = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    private String[] spinner = {"地域", "籍贯", "校友", "战友", "宗亲", "行业", "民族", "其他"};
    private String organizingCode;
    private int type;


    @Override
    protected void initIntentData(Intent callIntent) {
        groupCategoryId = callIntent.getStringExtra("groupCategoryId");
        type = callIntent.getIntExtra("type", -1);
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("编辑群资料").setLeftBtnIcon(R.mipmap.back_black).setOnLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtils.finishActivity(CreateGroupOnlyActivity.this);
            }
        });
    }

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected int initContentView() {
        UtilsStyle.setStatusBarMode(this, true);
        RxBarTool.FlymeSetStatusBarLightMode(getWindow(), true);
        RxBarTool.MIUISetStatusBarLightMode(getWindow(), true);
        return R.layout.activity_create_group_only;
    }

    @Override
    protected void initChildView() {
        mCetActivityCreateGroupProposer = findViewById(R.id.cet_activity_create_group_proposer);
        mCetActivityCreateGroupName = findViewById(R.id.cet_activity_create_group_name);
        mCetActivityCreateGroupCompanyIntroduce = findViewById(R.id.cet_activity_create_group_company_introduce);
        mBtnActivityCreateGroupUpdate = findViewById(R.id.btn_activity_create_group_update);
        mIvActivityCreateGroupCompanyIcon = findViewById(R.id.iv_activity_create_group_company_icon);
        mSpActivityStates = findViewById(R.id.sp_activity_states);

    }

    @Override
    protected void initChildData() {
        mBtnActivityCreateGroupUpdate.setOnClickListener(this);
        mIvActivityCreateGroupCompanyIcon.setOnClickListener(this);
        for (String s : spinner) {
            list.add(s);
        }
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        mSpActivityStates.setAdapter(adapter);
    }

    @Override
    protected void setChildViewListener() {

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_activity_create_group_company_icon:
                try {
                    InputMethodManager im = (InputMethodManager) CreateGroupOnlyActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(CreateGroupOnlyActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture(1);
                    } else {
                        ActivityCompat.requestPermissions(CreateGroupOnlyActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(CreateGroupOnlyActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }
                break;
            case R.id.btn_activity_create_group_update:
                String groupName = mCetActivityCreateGroupProposer.getText().toString().trim();
                String description = mCetActivityCreateGroupName.getText().toString().trim();
                String welcomeTips = mCetActivityCreateGroupCompanyIntroduce.getText().toString().trim();
                groupCategoryId = mSpActivityStates.getSelectedItemId() + 1 + "";
                CreateGroupInfoBean createGroupInfoBean = new CreateGroupInfoBean();
                createGroupInfoBean.name = groupName;//群名称
                createGroupInfoBean.description = description;//群介绍
                if (type != -1)
                    createGroupInfoBean.groupType = type == 1 ? "individual" : "plateform";//群类型
                createGroupInfoBean.groupCategoryId = groupCategoryId;//群分类id
                createGroupInfoBean.welcomeTips = welcomeTips;//欢迎语
                createGroupInfoBean.icon = picUrl1;//企业logo
                createGroupInfoBean.applicationPhoto = picUrl;//申请照片
                if (type == 2) {
                    createGroupInfoBean.plateformId = "1";
                    createGroupInfoBean.plateformName = "正气诚信平台";
                }
                showLoadingDialog();
                ApiManager.getApi().UpdateGroupInfo(createGroupInfoBean).enqueue(new NetCallBack<CreateGroupInfoBean>() {
                    @Override
                    protected void onSuccess(Call<CreateGroupInfoBean> call, Response<CreateGroupInfoBean> response) {
                        CreateGroupInfoBean createGroupInfoBean1 = response.body();
                        UIUtils.showToast("已提交审核");
                        ActivityUtils.finishActivity(CreateGroupOnlyActivity.this);
                    }

                    @Override
                    protected void hiddenProgress() {
                        hideLodingDialog();
                    }
                });
                break;
        }
    }

    private void takePicture(final int count) {
        DialogUtils.createPopwindow(this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH);
                Uri data;
                // 判断版本大于等于7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
                    data = FileProvider.getUriForFile(CreateGroupOnlyActivity.this, "com.braveman.im.fileprovider", file);
                    // 给目标应用一个临时授权
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    data = Uri.fromFile(file);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, data);
                CreateGroupOnlyActivity.this.startActivityForResult(intent, count == 0 ? REQUEST_CODE_TAKE_PHOTO : REQUEST_CODE_TAKE_ICON_PHOTO);


            }
        }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {

                Intent i = new Intent(
                        Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, count == 0 ? REQUEST_CAMERA_CODE : REQUEST_CAMERA_ICON_CODE);
            }
        }).showAtLocation(mTitleBarView, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 130);
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {
        switch (msg.what) {
            case 200: //图片
                int type = (int) msg.obj;
                String path = "";
                switch (type) {
                    case 2:
                        path = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                        Glide.with(CreateGroupOnlyActivity.this)//
                                .load(path)
                                .into(mIvActivityCreateGroupCompanyIcon);
                        toUpdata(path, 1);
                        break;
                    case 3:
                        path = picturePath1;
                        Glide.with(CreateGroupOnlyActivity.this)//
                                .load(path)
                                .into(mIvActivityCreateGroupCompanyIcon);
                        toUpdata(path, 1);
                        break;

                }
        }
    }

    private void toUpdata(String path, final int count) {
        File file = new File(path);
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        showLoadingDialog();
        ApiManager.getApi().uploadPic("image", filePart).enqueue(new NetCallBack<List<PicUpdateBean>>() {


            @Override
            protected void onSuccess(Call<List<PicUpdateBean>> call, Response<List<PicUpdateBean>> response) {
                UIUtils.showToast("图片上传成功");
                PicUpdateBean picUpdateBean = response.body().get(0);
                picUrl1 = picUpdateBean.url;
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case REQUEST_CODE_TAKE_PHOTO:
                    String filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                    new CompressPhotoThread(mHandler, filePath, 0).start();
                    break;
                //                 选择照片
                case REQUEST_CODE_TAKE_ICON_PHOTO:
                    String filePath1 = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                    new CompressPhotoThread(mHandler, filePath1, 2).start();
                    break;
                //                 选择照片
                case REQUEST_CAMERA_CODE:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    new CompressPhotoThread(mHandler, picturePath, 1).start();
                    break;
                case REQUEST_CAMERA_ICON_CODE:
                    Uri selectedImage1 = data.getData();
                    String[] filePathColumn1 = {MediaStore.Images.Media.DATA};
                    Cursor cursor1 = this.getContentResolver().query(selectedImage1,
                            filePathColumn1, null, null, null);
                    cursor1.moveToFirst();
                    int columnIndex1 = cursor1.getColumnIndex(filePathColumn1[0]);
                    picturePath1 = cursor1.getString(columnIndex1);
                    cursor1.close();
                    new CompressPhotoThread(mHandler, picturePath1, 3).start();
                    break;

            }
        }

    }

}
